﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace YArchitech.Public
{
	internal static class XElementExternsion
	{
		public static string GetAttribute(this XElement elem, string attName)
		{
			string result;
			try
			{
				result = elem.Attribute(attName).Value;
			}
			catch
			{
				result = string.Empty;
			}
			return result;
		}

		public static string GetName(this XElement elem)
		{
			return elem.GetAttribute("Name");
		}

		public static string GetText(this XElement elem)
		{
			return XElementExternsion.GetRibbonText(elem.GetAttribute("Text"));
		}

		public static string GetTooltip(this XElement elem)
		{
			return XElementExternsion.GetRibbonText(elem.GetAttribute("ToolTip"));
		}

		public static string GetExpandedContent(this XElement elem)
		{
			return XElementExternsion.GetRibbonText(elem.GetAttribute("ExpandedContent"));
		}

		public static string GetImage(this XElement elem)
		{
			return elem.GetAttribute("MenuImage");
		}

		public static string GetRibbonText(string text)
		{
			return text.Replace("\\n", Environment.NewLine);
		}

		public static int GetIndex(this XElement elem)
		{
			int result;
			try
			{
				result = (int)elem.Attribute("Index");
			}
			catch
			{
				result = int.MaxValue;
			}
			return result;
		}

		public static XElement GetChildElementByName(this XElement elem, string name)
		{
			IEnumerable<XElement> enumerable = from xe in elem.Elements()
			where xe.GetName() == name
			select xe;
			if (enumerable == null || enumerable.Count<XElement>() == 0)
			{
				return null;
			}
			return enumerable.First<XElement>();
		}

		public static IEnumerable<XElement> GetSortedChildElements(this XElement elem)
		{
			IEnumerable<XElement> result;
			try
			{
				if (!elem.HasElements)
				{
					result = null;
				}
				else
				{
					result = from child in elem.Elements()
					orderby child.GetIndex()
					select child;
				}
			}
			catch
			{
				result = null;
			}
			return result;
		}
	}
}
